Skip to main content

Prefix Match

Prefix matching means NGINX matches a request based on the beginning (prefix) of the URI.

If the request URI starts with a given path, that location block is a candidate.

Request URI: /images/logo.png
Prefix: /images/
→ MATCH

This type of match is used for: Static files, Application routes, API paths, Proxies, Almost everything in real-world configs

location /path/ {
...
}
  • /path/ is a literal prefix
  • Matching is case-sensitive
  • No regex involved

Example

server {
listen 80;
server_name example.com;

root /var/www/html;

location /images/ {
root /var/www/assets;
}
}

How This Works

  • Request: /images/logo.png
  • Matching logic
    • Does /images/logo.png start with /images/? → Yes
    • NGINX selects this location
  • File served: /var/www/assets/images/logo.png
  • Because: root /var/www/assets;

Prefix Matching Priority (Very Important)

NGINX evaluates location blocks in this order:

  1. Exact match (location = /path)
  2. Longest prefix match (location /path/)
  3. Regex match (location ~)
  4. Default (location /)

Among prefix matches, the longest matching prefix wins.

location /api/ {
proxy_pass http://backend_api;
}

location /api/v1/ {
proxy_pass http://backend_v1;
}

Requests

RequestMatched Location
/api/users/api/
/api/v1/users/api/v1/

The Root (/) Prefix (Catch-All)

location / {
try_files $uri $uri/ =404;
}
  • / matches everything
  • Acts as the default location
  • Used when no other location matches

Prefix Match with ^~ (Stop Regex Checks)

location ^~ /static/ {
root /var/www/static;
}
  • If this prefix matches:
    • NGINX skips regex checks
  • Improves performance
  • Prevents regex from overriding this location

Why ^~ Matters

location ^~ /images/ {
root /var/www/images;
}

location ~ \.jpg$ {
root /var/www/jpg;
}
  • Request: /images/photo.jpg
  • Result:
    • Prefix /images/ matches
    • ^~ stops regex
    • Served from /var/www/images

Without ^~, the regex location could win.

Prefix Matching vs Exact Matching

location = /login {
return 403;
}
RequestMatched
/loginExact match
/login/Prefix /

Exact match is higher priority than prefix.

Prefix Matching with alias (Common Pitfall)

location /download/ {
alias /var/files/;
}
  • Request: /download/file.zip
  • File served: /var/files/file.zip

With alias, the location path is replaced, not appended.

Common Use Cases for Prefix Locations

  1. Static files
location /static/ {
root /var/www;
expires 30d;
}
  1. API routing
location /api/ {
proxy_pass http://api_backend;
}
  1. Application sections
location /admin/ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;
}

Common Mistakes

  • Forgetting trailing slash (/path vs /path/)
  • Expecting prefix matching to behave like regex
  • Misusing root vs alias
  • Not understanding longest prefix wins
  • Letting regex override important prefixes